package leetcode21;

import domain.ListNode;

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = null;
        ListNode index = head;
        while (list1 != null || list2 != null) {
            ListNode add = null;
            if (list1 == null) {
                add = list2;
                list2 = list2.next;
            } else if (list2 == null) {
                add = list1;
                list1 = list1.next;
            } else {
                if(list1.val <= list2.val){
                    add = list1;
                    list1 = list1.next;
                }else{
                    add = list2;
                    list2 = list2.next;
                }
            }
            if(head==null){
                head = add;
                index = head;
            }else{
                index.next = add;
                index = index.next;
            }
        }
        return head;
    }
}